package ics314;

/**
 * this file creates an .ics file
 * @author Barroga, Jordan
 * 	   Morimoto, Satoshi
 * 	   Shao, Nina
 */

import java.io.*;
import java.util.Scanner;

public class ICScreation {

	/** the file name that the .ics will be saved as **/
	String fileName = "";
	/** string containing the encoding type **/
	String ext = ".ics"; 
	// should i use FileWriter or FileOutputStream
	/** **/
	static String[] field = {"BEGIN:","VERSION:","GEO:","BEGIN:","DTSTART:","DTEND:",
								"DESCRIPTION:","LOCATION:","SUMMARY:","X-WR-TIMEZONE:","END:","END:"};
	/** **/
	static String[] fieldValues = new String[12];
	
	/**
	 * this is a constructor that uses the the parameters to set
	 * up the rest of the data fields so that there will not be
	 * any errors when we are creating the file.
	 * @param name the name of the file that we will be creating
	 * @throws IOException 
	 */
	public ICScreation(String name) throws IOException{
		this.fileName = name;
		this.writeToFile();
	}
	
	/**
	 * creates the .ics
	 * @return true when creation of file is successfull
	 * @return false when creation of file has failed
	 * @throws IOException when the file to be created already exist
	 */
	public boolean createFile() throws IOException{
		boolean created = false;
		try{
			File newFile = new File(fileName + ".ics");
            if(!newFile.exists()){
				created = newFile.createNewFile();
            }
		} catch (IOException e){
			
		}
		return created;
	}
	
	/**
	 * adds content to the .ics file
	 * @throws IOException 
	 */
	public void writeToFile() throws IOException{
		//writing to a different file and im not sure if its even a .ics file
		fieldValues[0] = "VCALENDAR";
		fieldValues[1] = "2.0";
		fieldValues[11] = "VCALENDAR";
		Writer output = new BufferedWriter(new FileWriter(fileName+"2"+ext));
		output.write(icsFormat());
		output.close();
		System.out.println("your file has been written to.");
	}
	
	/**
	 * adjust the content, to be placed within the .ics file,
	 * to certain specifications in order to be compliant with
	 * the standard formatting.
	 */
	public static String icsFormat(){
		String result = "";
		for(int i=0; i<field.length; i++){
			result = result + field[i] + fieldValues[i] + "\n";
		}
		return result;
	}





	//checks for a valid date
	public static boolean checkValidDate (String month, String dayInput, String year){
			
		int day = Integer.parseInt(dayInput);
		int monthNum = 0;
		String [] months = {"JAUNARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
				"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
		boolean dateVerify = false;

		if (Double.parseDouble(year) >= 2012){ //adds the year to the date String if valid year
			dateVerify = true; 
		}
		
		if (dateVerify == true){ //if year is valid moves on to check month validity
			
			dateVerify = false;
			for (int n=0; n<12; n++){ //adds the month to the date String if valid month
				if (month.toUpperCase().equals(months[n])){
					monthNum = n+1;
					dateVerify = true;
				}
			}
		}
		if (dateVerify == true){ //if month is also valid checks for day validity
			
			dateVerify = false;
			if ( (monthNum>0) && (monthNum<13) && (day>0) && (day<32) ){ //matches # of days to each month
				
				// 30 days in April, June, September, November
				if ( ((monthNum == 4) || (monthNum == 6) || (monthNum == 9) || (monthNum == 11)) && (day<31) ) {
					dateVerify = true;
					return dateVerify;
				}
				// 28 days in February (leap year no accounted for)
				if ((monthNum == 2) && (day<29)){
					dateVerify = true;
					return dateVerify;
				}
				// 31 days in Jan, Mar, May, July, Aug, Oct, Dec
				if ( ((monthNum == 1) || (monthNum == 3) || (monthNum == 5) || (monthNum == 7) || 
						(monthNum == 8) || (monthNum == 10) || (monthNum == 12)) && (day<32) ) {
					dateVerify = true;
					return dateVerify;
				}
			}
		}
		return dateVerify;
	}	
	
	
	//returns the valid date
	public static String returnDate (String month, String dayInput, String year){
	
		String [] months = {"JAUNARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
				"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
		
		String date = year.trim(); //add year to date String
		
		for (int n=0; n<12; n++){ //adds the month to the date String 
			if (month.toUpperCase().equals(months[n])){
				if (n<10){
					date = date + "0" + (n+1);
				}
				else {
					date = date + (n+1);
				}
			}
		}
		int newDay = Integer.parseInt(dayInput)+1;
		if (newDay < 10){ //adds the day to the date String
			date = date + "0" + newDay;
		}
		else {
			date = date + newDay;
		}
		return date;
	}
	
	//checks the validity of a time
	public static boolean checkValidTime (String time, String amPm){
		
		String hour = time.substring(0,time.indexOf(':'));
		String min = time.substring(time.indexOf(':')+1);
		boolean timeVerify = false;
		
		if ((Integer.parseInt(hour)>0) && (Integer.parseInt(hour)<13)){ //checks if hour is 0<x<13
			timeVerify = true;
		}
		if (timeVerify == true){
			
			timeVerify = false;
			if ( (Integer.parseInt(min)>-1) && (Integer.parseInt(min)<60) ){ //checks if min is 00<x<60
				timeVerify = true;
			}
		}
		if (timeVerify == true){ //checks if it matches either am or pm
			timeVerify = false;
			if (amPm.trim().toUpperCase().equals("AM")){
				timeVerify = true;
			}
			else if (amPm.trim().toUpperCase().equals("PM")){
				timeVerify = true;
			}
		}

		return timeVerify;
	}
	
	
	// if the timeString is valid returns the time as a String
	public static String returnTime (String time, String amPm){
		String hour = time.substring(0,time.indexOf(':'));
		String min = time.substring(time.indexOf(':')+1);
		String timeString = "";
		
		if (Integer.parseInt(hour) < 10){
			timeString = "0";
		}
		timeString = "T" + timeString + hour;
		timeString = timeString + min + "00";
		if (amPm.trim().toUpperCase().equals("PM")){
			timeString = timeString + "Z";
		}
		return timeString;
	}




	
	/**
	 * used for testing to ensure that all the methods and
	 * constructors work properly.
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException{

		Scanner input = new Scanner (System.in);
		String type = "";
		int count = 2;
		
		//Date Input
		String date = "";	
		boolean dateVerify = false;
		while (dateVerify == false){ //verifies date
			System.out.print("Please input a date (ex. April 26 2012): ");
			String month = input.next();
			String dayInput = input.next();
			String year = input.nextLine();
			dateVerify = checkValidDate(month, dayInput, year);
			if (dateVerify == true){
				date = returnDate(month, dayInput, year);
			}			
		}	
		
		//Geographic Location; GEO:
		System.out.println("Please Input your Geographic Location.");
		System.out.print("Latitude (ex. 37.386013): ");
		float lat = input.nextFloat(); 
		System.out.print("Longitude: ");
		float lon = input.nextFloat();
		input.nextLine();
		String info = lat + ";" + lon;
		fieldValues[count] = info + '\n';
		count++;
		
		//Classification Input; BEGIN:
		System.out.print("What would you like to schedule (ex. Event): ");
		type = input.nextLine(); 
		fieldValues[count] = "V" + type.toUpperCase();
		count++;
		
		//Start time Input; DTSTART: 
		System.out.print("Start time (ex. 6:30 pm): ");
		String stime = input.next(); //DTSTART (start time)
		String amOrpm = input.nextLine();
		boolean timeVerify = checkValidTime(stime, amOrpm);
		String starttime = "";
		if (timeVerify == true){
			String hour = stime.substring(0,stime.indexOf(':'));
			String min = stime.substring(stime.indexOf(':')+1);
			int newhour = Integer.parseInt(hour)-2;
			String newTime = newhour + ":" + min;
			starttime = returnTime(newTime, amOrpm);
		}
		fieldValues[count] = date + starttime;
		count++;
		
		//End time Input; DTEND: 
		System.out.print("End time (ex. 6:30 pm): ");
		String etime = input.next().trim(); //DTEND (end time)
		amOrpm = input.nextLine().trim();
		timeVerify = checkValidTime(etime, amOrpm);
		String endtime = "";
		if (timeVerify == true){
			String hour = etime.substring(0,etime.indexOf(':')).trim();
			String min = etime.substring(etime.indexOf(':')+1).trim();
			int newhour = Integer.parseInt(hour)-2;
			String newTime = newhour + ":" + min;
			endtime = returnTime(newTime, amOrpm);
		}
		fieldValues[count] = date + endtime;
		count++;
		
		
		//Comments Input; DESCRIPTION:
		System.out.print("Description/Comments: ");
		info = input.nextLine(); 
		fieldValues[count] = info;
		count++;
		
				
		//Location Input; LOCATION: 
		System.out.print("Location (ex. UH Manoa): ");
		info = input.nextLine(); 
		fieldValues[count] = info;
		count++;
		
		//Resources Input; SUMMARY: 
		System.out.print("Title of Event: ");
		info = input.nextLine(); 
		fieldValues[count] = info;
		count++;
		
				
		//Time zone input; X-WR-TIMEZONE:
		System.out.print("Please input your time zone (ex: (GMT-10:00) Hawaii Time): ");
		info = input.nextLine(); 
		fieldValues[count] = info;
		count++;
		
		//END:
		fieldValues[count] = "V" + type.toUpperCase();
		
		ICScreation test = new ICScreation("tester");
		
	}
	
}

